import { useFetch, FetchOptions, FetchResponse } from '#app';
import { useRuntimeConfig } from '#app';

// 定义更明确的类型别名
type HttpMethod = 'GET' | 'POST' | 'PUT' | 'DELETE' | 'PATCH';
type ApiHeaders = Record<string, string>;

// 提取获取授权头部的函数
const getAuthorizationHeader = (): string => {
    if (import.meta.client) {
        const token = localStorage.getItem('Authorization');
        return token? `Bearer ${token}` : '';
    }
    return '';
};

const apiCore = <T>(url: string, options: FetchOptions & { method: HttpMethod }): Promise<FetchResponse<T>> => {
    const config = useRuntimeConfig();
    const headers: ApiHeaders = {
        Authorization: getAuthorizationHeader(),
        ...(options.headers || {})
    };
    const newOptions: FetchOptions = {
        baseURL: config.public.apiBase,
        headers,
        ...options,
        onRequest({ options: reqOptions }) {
            console.log('Request options:', reqOptions);
        },
        onResponse({ response }) {
            console.log('Response:', response);
        },
        onResponseError({ response }) {
            console.error('API Error:', response);
            throw new Error(`API Error: ${response.statusText}`);
        }
    };
    return useFetch<T>(url, newOptions);
};

const createApiMethod = <T>(method: HttpMethod) => {
    const methodHandlers: Record<HttpMethod, (paramsOrData?: Record<string, any>) => Partial<FetchOptions & { method: HttpMethod }>> = {
        'GET': (paramsOrData) => paramsOrData? { query: paramsOrData } : {},
        'POST': (paramsOrData) => paramsOrData? { body: JSON.stringify(paramsOrData) } : {},
        'PUT': (paramsOrData) => paramsOrData? { body: JSON.stringify(paramsOrData) } : {},
        'DELETE': (paramsOrData) => paramsOrData? { query: paramsOrData } : {}
    };
    return (url: string, paramsOrData?: Record<string, any>): Promise<T> => {
        const options = methodHandlers[method](paramsOrData);
        return apiCore<T>(url, {
            method,
            ...options
        }).then(res => {
            return res.data.value;
        });
    };
};

export const GET_API = createApiMethod<any>('GET');
export const POST_API = createApiMethod<any>('POST');
export const PUT_API = createApiMethod<any>('PUT');
export const DELETE_API = createApiMethod<any>('DELETE');
export const PATCH_API = createApiMethod<any>('PATCH');